// 引入 .env 配置
const getBaseUrl = () => 'http://127.0.0.1:8080'

// 处理401错误的函数
const handle401Error = () => {
  // 清除本地存储的token和用户信息
  wx.removeStorageSync('Authorization');
  wx.removeStorageSync('userInfo');
  
  // 清除全局变量
  const app = getApp();
  app.Authorization = '';
  app.userInfo = {};
  
  // 显示提示信息
  wx.showToast({
    title: '登录已过期，请重新登录',
    icon: 'none',
    duration: 1500
  });
  
  // 延迟跳转到登录页面
  setTimeout(() => {
    wx.switchTab({
      url: '/pages/mine/mine'
    });
  }, 1500);
};

// 封装请求方法
const request = (options) => {
  const baseUrl = getBaseUrl();
  const { url, method = 'GET', data, header = {} } = options;
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method,
      data,
      header: {
        'Content-Type': 'application/json',
        'Authorization': getApp().Authorization || null,
        ...header
      },
      success: (res) => {
        if (res.data.code === 401) {
          // 处理401未授权错误
          handle401Error();
          reject(res);
        } else if (res.data.code >= 200 && res.data.code < 300) {
          resolve(res.data);
        } else {
          reject(res);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
};

export default request;